package cn.ibizlab.util.security;

import cn.ibizlab.util.web.Sm3Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * sm3密码加密器
 */
@Slf4j
@Component
@ConditionalOnExpression("'${ibiz.auth.passwordStorageMode:none}'.equals('sm3')")
public class SM3PasswordEncoder implements PasswordEncoder {

    private static final PasswordEncoder INSTANCE = new SM3PasswordEncoder();

    @Override
    public String encode(CharSequence rawPassword) {

        if (ObjectUtils.isEmpty(rawPassword)) {
            log.warn("Empty rawPassword");
            return null;
        }

        String password = rawPassword.toString();
        if (password.length() != 64) {
            password = Sm3Util.encrypt(rawPassword.toString());
        }
        return password;
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {

        if (ObjectUtils.isEmpty(encodedPassword)) {
            log.warn("Empty encoded password");
            return false;
        }

        String password = null;
        if (!ObjectUtils.isEmpty(rawPassword)) {
            password = rawPassword.toString();
            if (password.length() != 64)
                password = Sm3Util.encrypt(password);
        }
        return encodedPassword.equals(password);
    }

    public static PasswordEncoder getInstance() {
        return INSTANCE;
    }

}
